#include "include/muduo/net/TcpClient.h"
#include "include/muduo/net/EventLoopThread.h"
#include "include/muduo/net/TcpConnection.h"
#include "include/muduo/base/CountDownLatch.h"
#include <iostream>
#include <functional>
#include <unordered_map>


class TranslateClient
{
public:
    TranslateClient(const std::string& ip, int port)
        :_latch(1), _client(_loopthread.startLoop(), muduo::net::InetAddress(ip, port), "TranslateClient")
    {
         //std::bind 是一个函数适配器函数，对指定的函数进行参数绑定
        //typedef std::function<void (const TcpConnectionPtr&)> ConnectionCallback;
        _client.setConnectionCallback(std::bind(&TranslateClient::onConnection, this, std::placeholders::_1));

        //typedef std::function<void (const TcpConnectionPtr&,Buffer*,Timestamp)> MessageCallback;
        _client.setMessageCallback(std::bind(&TranslateClient::onMessage, this, std::placeholders::_1
                                  , std::placeholders::_2, std::placeholders::_3));
    }

    //连接服务器是异步操作的，可能还没有链接成功，就返回了
    //所以这里需要借助CountDownLatch进行同步，发起连接后等待，连接成功后返回
    void connect()
    {
        //连接服务器
        _client.connect();
        _latch.wait(); //阻塞等待，直到链接建立成功返回
    }

    //向服务器发送数据，
    bool send(const std::string& msg)
    {   
        if(_conn->connected())
        {
            _conn->send(msg);
            return true;
        }
            
        return false;
    }

private:
    //连接建立成功后的回调函数
    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        std::cout << "子线程tid:" << gettid() << std::endl;
        if(conn->connected())
        {
            _latch.countDown(); //唤醒主线程的阻塞
            _conn = conn;
        }
        else
        {
            //关闭连接的操作
            _conn.reset();
        }
    }

    //收到消息时候的回调函数
    void onMessage(const muduo::net::TcpConnectionPtr& conn, muduo::net::Buffer* buff, muduo::Timestamp)
    {
        std::cout << "子线程tid:" << gettid() << std::endl;
        std::cout << buff->retrieveAllAsString() << std::endl;
    }
private:
    muduo::CountDownLatch _latch;
    // 一旦实例化成功，创建子Reactor线程立刻开始事件监控循环,主线程负责发起连接，等待，
    // 然后子Reactor线程负责连接回调唤醒，消息处理的回调
    muduo::net::EventLoopThread _loopthread; 
    muduo::net::TcpClient _client;
    muduo::net::TcpConnectionPtr _conn;
};

int main()
{
    std::cout << "主线程tid:" << gettid() << std::endl;
    TranslateClient client("127.0.0.1", 8085);
    client.connect();

    while(1)
    {
        std::string buff;
        std::cin >> buff;
        client.send(buff);
    }

    return 0;
}